package com.xlx.ui.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.xlx.ui.domain.DTO.UserDTO;
import com.xlx.ui.domain.MO.User;
import com.xlx.ui.domain.VO.ResultBody;
import com.xlx.ui.service.AdminUserService;
import com.xlx.ui.service.error.errorImpl.BizException;
import com.xlx.ui.service.error.errorImpl.ResponseCodeEnum;
import com.xlx.ui.service.token.TokenService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Description:
 * @author: 张川
 * @date: 2021-03-18 22:17
 */
@RestController
@RequestMapping("/admin/user")
public class AdminUserController {

    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private TokenService tokenService;


    @PostMapping("/login")
    public ResultBody login(@RequestBody JSONObject jsonObject) {
        JSONObject response = new JSONObject();
        String username = jsonObject.get("username").toString();
        String password = jsonObject.get("password").toString();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            throw new BizException(ResponseCodeEnum.USER_NULL);
        }
        User user = adminUserService.login(username, password);
        String token = tokenService.getToken(user);
        response.put("token", token);
        return ResultBody.success(response);
    }

    @GetMapping("/info")
    public ResultBody userinfo(String token) {
        User info = adminUserService.getInfo(token);
        return ResultBody.success(info);
    }


    @ApiOperation(value = "获取所有用户")
    @GetMapping("/all")
    public ResultBody getalluser(UserDTO userDTO) {
        return adminUserService.getAll(userDTO);
    }

    @ApiOperation(value = "添加用户")
    @PostMapping("")
    public ResultBody updateUser(@RequestBody UserDTO userDTO) {
        return adminUserService.add(userDTO) ? ResultBody.success() : ResultBody.error(ResponseCodeEnum.ADD_ERROR);
    }


}
